package cn.livingCloud.controller.core;

import cn.livingCloud.dto.CaseCategoryFormDto;
import cn.livingCloud.dto.CaseCategoryListDto;
import cn.livingCloud.service.CaseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;

/**
 * Created by 唐旭 on 2016/6/2.
 */
@Controller
@RequestMapping("/admin/cmc/category")
public class CaseCategoryController {

    @Autowired
    private CaseCategoryService service;

    @RequestMapping("/list.htm")
    public String list(CaseCategoryListDto listDto, Model model) {
        service.loadList(listDto);
        model.addAttribute("listDto", listDto);
        return "cmc/category/list";
    }

    @RequestMapping("/edit.htm")
    public String editForm(String uuid, String parentUuid, Model model) {
        CaseCategoryFormDto formDto = service.loadForm(uuid, parentUuid);
        model.addAttribute("formDto", formDto);
        return "cmc/category/edit";
    }

    @RequestMapping(value = "/edit.htm", method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("formDto") @Valid CaseCategoryFormDto formDto, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "cmc/category/edit";
        }
        service.update(formDto);
        model.addAttribute("edit", "success");
        if (formDto.getParent() != null) {
            model.addAttribute("parentUuid", formDto.getParent().getUuid());
        }
        return "redirect:list.htm";
    }

    @RequestMapping("/content.htm")
    public String showContent(@RequestParam("uuid") String uuid, Model model) {
        String content = service.loadContent(uuid);
        model.addAttribute("content", content);
        return "cmc/category/content";
    }

    @RequestMapping("/delete.htm")
    public String delete(@RequestParam("uuid") String uuid, Model model) {
        service.delete(uuid);
        model.addAttribute("delete", "success");
        return "redirect:list.htm";
    }

}
